<?php
/**
 * Escape a URL for output
 * As I was working on a Wordpress project, I saw they were using an esc_url
 * function when outputting an URL. So far for this project I've been either not
 * escaping URLs or escaping using the standard escape() helper. This helper is
 * much better suited to the purpose than that one. It is based on Wordpress's
 * esc_url function.
 *
 * @package 	Visi
 * @subpackage 	View Helpers
 * @author 		Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright 	Luke Visinoni <luke.visinoni@gmail.com>
 * @version 	$Id$
 */
class Visi_View_Helper_EscapeUrl extends Zend_View_Helper_Abstract {

	/**
	 * Escape URL
	 * A Wordpress inspired function for escaping URLs. The difference is that
	 * the Wordpress function checks the protocol and allows you to also escape
	 * for HTML output. This function doesn't do that. If you need to escape for
	 * HTML output, just pass the output of this to the regular escape() helper.
	 * 
	 * @param string URL to be escaped
	 * @return string The escaped URL
	 */
    public function escapeUrl($url = null) {
    
		if (is_null($url)) return $this;
		
		$original_url = $url;
		if ('' == $url) {
			return $url;
		}
		$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
		$strip = array('%0d', '%0a', '%0D', '%0A');
		$url = deep_str_replace($strip, $url);
		$url = str_replace(';//', '://', $url);
		/**
		 * If the URL doesn't appear to contain a scheme, we
		 * presume it needs http:// appended (unless a relative
		 * link starting with / or a php file).
		 */
		if (strpos($url, ':') === false &&
			substr($url, 0, 1 ) != '/' && substr($url, 0, 1) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url)) {
			$url = 'http://' . $url;
		}
		return $url;
    
    }
	
	public function encode($str, $raw = false) {
	
		if ($raw) {
			return rawurlencode($str);
		} else {
			return urlencode($str);
		}
	
	}

}